package com.mylg.craw.house.baiduyun;

import com.mylg.craw.house.baiduyun.dto.AccessTokenDto;
import com.mylg.craw.house.baiduyun.dto.Image2TextRequestDto;
import com.mylg.craw.house.baiduyun.dto.Image2TextResponseDto;
import com.mylg.craw.house.government.util.Base64ToImage;
import com.mylg.craw.house.util.JacksonUtils;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.math3.util.Pair;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;

import java.util.HashMap;
import java.util.Map;

@Log4j2
@Service
public class WenXinYiYan {
    //
    private static final String API_KEY = "4XbDsGic5NLSLo9KQ4AQOsdF";

    private static final String SECRET_KEY = "yUTgGVrmO4NFz6QpqIRPaNWkWJEHkWWh";

    private static final String IMAGE2TEXT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/image2text/fuyu_8b?access_token={access_token}";

    private long expireTime;

    private String accessToken;
    @Resource
    private RestClient restClient;

    public String accessToken() {
        long current = System.currentTimeMillis();
        if (StringUtils.isEmpty(accessToken) || current > expireTime) {
            Pair<String, Long> res = curlAccessToken();
            if (res != null) {
                accessToken = res.getFirst();
                expireTime = res.getSecond();
            }
        }
        return accessToken;
    }

    private Pair<String, Long> curlAccessToken() {
        Map<String, String> param = new HashMap<>();
        param.put("client_id", API_KEY);
        param.put("client_secret", SECRET_KEY);
        String res = restClient.post()
                .uri("https://aip.baidubce.com/oauth/2.0/token?client_id={client_id}&client_secret={client_secret}&grant_type=client_credentials", param)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve().body(String.class);

        AccessTokenDto dto = JacksonUtils.readValue(res, AccessTokenDto.class);
        if (dto == null || !StringUtils.isEmpty(dto.getError())) {
            log.warn("获取token异常,res={}", res);
            return null;
        }

        log.info("输出结果:{}", res);

        long expireTime = System.currentTimeMillis() + (dto.getExpiresIn() - 60) * 1000;
        return Pair.create(dto.getAccessToken(), expireTime);
    }


    public void image2Text(String image) {
       // String accessToken = accessToken();
        String accessToken = "24.8742bdf4f511cd4b1975345f348cfb23.2592000.1719935140.282335-77582284";
        Image2TextRequestDto requestDto = new Image2TextRequestDto();
        requestDto.setPrompt("表格标题和内容");
        requestDto.setImage(Base64ToImage.input(image));
        Map<String, String> tokens = new HashMap<>();
        tokens.put("access_token", accessToken);
        String res = restClient.post()
                .uri(IMAGE2TEXT_URL, tokens)
                .contentType(MediaType.APPLICATION_JSON)
                .body(requestDto)
                .retrieve().body(String.class);

        Image2TextResponseDto dto = JacksonUtils.readValue(res, Image2TextResponseDto.class);
        if (dto == null || dto.getErrorCode() != null) {
            log.warn("获取结果异常,res={}", res);
            return;
        }

        log.info("输出结果:{}", res);
    }
}
